package cn.com.ytst.data.integration.controller;


import com.alibaba.datax.common.util.Configuration;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ytst.framework.common.StringTools;
import com.ytst.framework.common.filter.FilterUtil;

import cn.com.ytst.data.integration.CommonKey;
import cn.com.ytst.data.integration.manager.job.QuartzManager;
import cn.com.ytst.data.integration.util.DataBaseType;
import cn.com.ytst.data.integration.util.PageUtil;
import cn.com.ytst.data.integration.util.filter.FileFilter;
import cn.com.ytst.data.integration.vo.AjaxResult;
import cn.com.ytst.data.integration.vo.DataTable;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;


/**
 * 
* @ClassName: FtpController 
* @Description: 
* @author 123774135@qq.com 
* @date 2019年5月7日 下午5:26:13 
*
 */
@Controller
@RequestMapping
public class FtpController {

	    private Logger logger = LoggerFactory.getLogger(FtpController.class);
	
	    @Value("${filepath}")
		private String filepath ; 

		
		private static final String LINE_TAG = "/";
		
		private static final String POINT_TAG = ".";
		
		@Autowired
		private QuartzManager quartzManager;

		@RequestMapping(value = "/ftp/grid", method = RequestMethod.POST)
		@ResponseBody
		public DataTable<JSONObject> grid(HttpServletRequest request) throws IOException {
			String id = request.getParameter("id");
			String pageNumber = StringTools.isBlank(request.getParameter("pageNum"))?"1":request.getParameter("pageNum");
			String pageSize =  StringTools.isBlank(request.getParameter("pageSize")) ? "10":request.getParameter("pageSize");
			String namepo = request.getParameter("name");
			String syncTypePo = request.getParameter("syncType");
			String sourceType = request.getParameter("sourceType");
			List<File> list = FileFilter.fiterFile(filepath+File.separator+"ftp", "ftp");
			JSONObject value = new JSONObject();
			if(!StringTools.isBlank(id)) {
				value.put("id", id+".json");
			}
			if(!StringTools.isBlank(namepo)) {
				value.put("name", namepo);
			}
			if(!"-1".equals(syncTypePo)) {
				value.put("syncType", syncTypePo);
			}
			if(!StringTools.isBlank(sourceType)) {
				value.put("path", sourceType);
			}
			
			List<JSONObject> list_json = Lists.newArrayList();
			if (!list.isEmpty()) {
				for (File f : list) {
					JSONObject jsonObject = new JSONObject();
					Configuration configuration = Configuration.from(FileUtils.readFileToString(f, "utf-8"));
					String prot = configuration.getString(CommonKey.FTP_PORT_TAG);
					String username = configuration.getString(CommonKey.FTP_USERNAME_TAG);
					String name = configuration.getString(CommonKey.FTP_NAME_TAG);
					String path = configuration.getString(CommonKey.FTP_REMOTEPATH_TAGE);
					String host = configuration.getString(CommonKey.FTP_HOST_TAG);
					String cronexpress = configuration.getString(CommonKey.HTTP_CORN_TAG);
					String dbtype = configuration.getString(CommonKey.DBWRITE_DBTYPE_TAG);
					String syncType = configuration.getString(CommonKey.FTP_SYNC_TYPE);
					String table = configuration.getString(CommonKey.DBWRITE_TABLE_TAG);
					jsonObject.put("name", name);
					jsonObject.put("table", table);
					jsonObject.put("username", username);
					jsonObject.put("syncType", syncType);
					jsonObject.put("host", host);
					jsonObject.put("prot", prot);
					jsonObject.put("path", path);
					jsonObject.put("id", f.getName());
					jsonObject.put("cronexpress", cronexpress);
					jsonObject.put("dbtype", dbtype);
					//String status = "";
					//String previousFireTime = "";
					//String nextFireTime = "";
//					TriggerState triggerState =	quartzManager.triggerState(name, TaskManager.GROUP_NAME);
//					if(null == triggerState) {
//						status = "不存在";
//					}else {
//						String state = triggerState.name();
//						switch (state) {
//						case "NONE":
//							status = "不存在";
//							break;
//						case "NORMAL":
//							status = "正常";
//							break;
//						case "PAUSED":
//						status = "停止";
//						break;
//						case "COMPLETE":
//							status = "完成";
//							break;
//						case "ERROR":
//							status = "错误";
//							break;
//						case "BLOCKED":
//							status = "阻塞中";
//							break;
//						default:
//							break;
//						}
//						Trigger trigger = 	quartzManager.getTrigger(name);
//						if(null == trigger) {
//
//						}else {
//							nextFireTime = DateUtil.formatDate(trigger.getNextFireTime(),DateUtil.format1);//下次触发时间
//							previousFireTime = null == trigger.getPreviousFireTime() ? "" : DateUtil.formatDate(trigger.getPreviousFireTime(), DateUtil.format1)	;//上一次触发时间
//						}
					//}
//					jsonObject.put("status", status);
//					jsonObject.put("nextFireTime", nextFireTime);
//					jsonObject.put("previousFireTime", previousFireTime);
					list_json.add(jsonObject);
				}
			}
			List<JSONObject> filters = this.doSearch(list_json, value);
			DataTable<JSONObject> dataTable = new DataTable<>();
			dataTable.setRows(PageUtil.startPage(filters,Integer.parseInt(pageNumber),Integer.parseInt(pageSize)));
			dataTable.setTotal(filters.size());
			dataTable.setCode(0);
			dataTable.setMsg("");
			return dataTable;

		}
		
		
		private List<JSONObject>  doSearch(List<JSONObject> list_json,JSONObject value) {
			//进行条件筛选
		 	return FilterUtil.filterValues(list_json, jsonobject -> {
				if(value.isEmpty()) {
					return true;//说明没有查询条件
				}
				List<String> listflage = Lists.newArrayList();
				for(Map.Entry<String, Object> entry : value.entrySet()) {
					String val = java.util.Objects.toString(entry.getValue());
					String valofprarms = StringTools.mkString(jsonobject.getString(entry.getKey()));
					if(valofprarms.contains(val)) {
						listflage.add("true");
					}else {
						listflage.add("false");
					}
				}
				boolean filter_flage = listflage.contains("false")?false:true;
				return filter_flage;

			});
			
		}

		@RequestMapping(value = "/ftp/add", method = RequestMethod.GET)
		public ModelAndView add() {
			return new ModelAndView("/page/component/ftp/ftp-add");
		}
		
		
		@RequestMapping(value = "/ftp/edit/{id}", method = RequestMethod.GET)
		public ModelAndView edit(@PathVariable(value = "id") String id) {
			Configuration configuration = Configuration.from(new File(filepath+File.separator+"ftp"+LINE_TAG+id));
	    	Set<String> set = configuration.getKeys();
	    	Map<String,Object> map = Maps.newHashMap();
	    	for(String key : set) {
	    		int last_index = key.lastIndexOf(POINT_TAG);
	    		String end_key = key.substring(last_index+1);
	    		if("oracle".equals(configuration.get(key))) {
	    			 map.put("dbtype", "1");
	    		}else if("mysql".equals(configuration.get(key))) {
	    			map.put("dbtype", "2");
	    		}else {
	    			 map.put(end_key, configuration.get(key));
	    		}
	    	}
	    	
	    	map.put("rmotepath", map.get("remotepath[0]"));
	    	map.put("id", id);
	    	map.put("syncType", configuration.get(CommonKey.FTP_SYNC_TYPE));
	    	return  new ModelAndView("/page/component/ftp/ftp-edit",map);
			
		}
		
		@RequestMapping(value="/ftp/save",method= RequestMethod.POST)
	    @ResponseBody
	    public AjaxResult save(HttpServletRequest request) {
			String name = request.getParameter("name");
			String host = request.getParameter("host");
			String prot = request.getParameter("prot");
			String username = request.getParameter("username");
			String password = request.getParameter("password");
			String localpath = request.getParameter("localpath");
			String filesystem = request.getParameter("filesystem");
			String corn = request.getParameter("corn");
			String syncType = request.getParameter("syncType");
			String splitformate = request.getParameter("splitformate");
			String rmotepath = request.getParameter("rmotepath");
			String disname = request.getParameter("disname");
			String dbtype = request.getParameter("dbtype");
			String url = request.getParameter("url");
			String dbpassword = request.getParameter("dbpassword");
			String dbusername = request.getParameter("dbusername");
			String table = request.getParameter("table");
			String clonums = request.getParameter("clonums");
			String type = "ORACLE";
			File file = new File(filepath + File.separator + "ftp" + "/ftp_" + filesystem.toLowerCase() + ".json");
			if ("1".equals(dbtype)) {
				type = DataBaseType.ORACLE.name();
			} else if ("2".equals(dbtype)) {
				type = DataBaseType.MYSQL.name();
			}
			try {
				String str = FileUtils.readFileToString(new File(filepath + "/temp/ftp_temp.json"), "utf-8");
				FileUtils.write(file, str, "utf-8");//先预先创建一个文件
				Configuration configuration = Configuration.from(file);
				configuration.set(CommonKey.FTP_SYSTEM_TAG, filesystem);
				configuration.set(CommonKey.FTP_PORT_TAG, prot);
				configuration.set(CommonKey.FTP_HOST_TAG, host);
				configuration.set(CommonKey.FTP_NAME_TAG, name); //这个地方用list<Map<String,String>>
				configuration.set(CommonKey.FTP_USERNAME_TAG, username);
				configuration.set(CommonKey.FTP_PWD_TAG, password);
				configuration.set(CommonKey.FTP_REMOTEPATH_TAGE, rmotepath);
				configuration.set(CommonKey.FTP_SYNC_TYPE, syncType);//待优化
				configuration.set(CommonKey.FTP_LOCALPATH_TAG, localpath);
				configuration.set(CommonKey.FTP_CORN_TAG, corn);
				configuration.set(CommonKey.FTP_SPLITFORMATE_TAG, splitformate);
				configuration.set(CommonKey.DBWRITE_DBNAME_TAG, disname);
				configuration.set(CommonKey.DBWRITE_DBTYPE_TAG, type.toLowerCase());
				configuration.set(CommonKey.DBWRITE_URL_TAGE, url);
				configuration.set(CommonKey.DBWRITE_USERNAME_TAG, dbusername);
				configuration.set(CommonKey.DBWRITE_PWD_TAG, dbpassword);
				configuration.set(CommonKey.DBWRITE_TABLE_TAG, table);
				configuration.set(CommonKey.DBWRITE_CLONUMS_TAG, clonums);
				String json = configuration.beautify();
				FileUtils.write(file, json, "utf-8");//先预先创建一个文件
				return AjaxResult.success(filesystem + "添加成功!");
			} catch (IOException e) {
				logger.error("", e);
			}
			return AjaxResult.error(filesystem + "添加失败!");

	    }
		
		
		@RequestMapping(value="/ftp/update",method= RequestMethod.POST)
	    @ResponseBody
	    public AjaxResult update(HttpServletRequest request) {
			String name = request.getParameter("name");
	    	String host = request.getParameter("host");
	    	String prot = request.getParameter("prot");
	    	String username = request.getParameter("username");
	    	String password = request.getParameter("password");
	    	String localpath = request.getParameter("localpath");
	    	String filesystem = request.getParameter("filesystem");
	    	String corn = request.getParameter("corn");
	    	String syncType = request.getParameter("syncType");
	    	String splitformate = request.getParameter("splitformate");
	    	String rmotepath = request.getParameter("rmotepath");
	    	String disname = request.getParameter("disname");
	    	String dbtype = request.getParameter("dbtype");
	    	String url = request.getParameter("url");
	    	String dbpassword = request.getParameter("dbpassword");
	    	String dbusername = request.getParameter("dbusername");
	    	String table = request.getParameter("table");
	    	String clonums = request.getParameter("clonums");
	    	String type = "ORACLE";
	    	File file = new File(filepath+File.separator+"ftp"+File.separator+filesystem.toLowerCase());
	    	if("1".equals(dbtype)) {
	    		type = DataBaseType.ORACLE.name();
	    	}else if("2".equals(dbtype)) {
	    		type = DataBaseType.MYSQL.name();
	    	} 
	    	try {
				 Configuration configuration = Configuration.from(file);
				 configuration.set(CommonKey.FTP_SYSTEM_TAG, filesystem);
				 configuration.set(CommonKey.FTP_PORT_TAG, prot);
				 configuration.set(CommonKey.FTP_HOST_TAG, host);
				 configuration.set(CommonKey.FTP_NAME_TAG,name); //这个地方用list<Map<String,String>>
				 configuration.set(CommonKey.FTP_USERNAME_TAG, username);
				 configuration.set(CommonKey.FTP_PWD_TAG,password);
				 configuration.set(CommonKey.FTP_REMOTEPATH_TAGE, rmotepath);
				 configuration.set(CommonKey.FTP_SYNC_TYPE,syncType);//待优化
				 configuration.set(CommonKey.FTP_LOCALPATH_TAG, localpath);
				 configuration.set(CommonKey.FTP_CORN_TAG,corn);
				 configuration.set(CommonKey.FTP_SPLITFORMATE_TAG,splitformate);
				 configuration.set(CommonKey.DBWRITE_DBNAME_TAG,disname);
				 configuration.set(CommonKey.DBWRITE_DBTYPE_TAG,type.toLowerCase());
				 configuration.set(CommonKey.DBWRITE_URL_TAGE,url);
				 configuration.set(CommonKey.DBWRITE_USERNAME_TAG,dbusername);
				 configuration.set(CommonKey.DBWRITE_PWD_TAG,dbpassword);
				 configuration.set(CommonKey.DBWRITE_TABLE_TAG,table);
				 configuration.set(CommonKey.DBWRITE_CLONUMS_TAG,clonums);
				 String json = configuration.beautify();
				 FileUtils.write(file, json, "utf-8");//先预先创建一个文件
				 return AjaxResult.success(filesystem+"添加成功!");
			} catch (IOException e) {
				logger.error("", e);
			}
	    	 return AjaxResult.error(filesystem+"添加失败!");

	    }
		
		
		
//		@RequestMapping(value="/ftp/start",method= RequestMethod.POST)
//	    @ResponseBody
//	    public AjaxResult start(String id) {
//	    	try {
//	    		File file = new File(filepath+File.separator+"ftp"+LINE_TAG+id);
//	    		Configuration configuration = Configuration.from(file);
//	    		String name = configuration.getString(CommonKey.FTP_NAME_TAG);
//	    		String cronexpress = configuration.getString(CommonKey.FTP_CORN_TAG);
//	    		quartzManager.addTask(name, name, QuartzJobFactoryDisallowConcurrentExecution.class, cronexpress, "engin", ftpEngine, filepath+LINE_TAG+"ftp"+LINE_TAG+id);
//	    		quartzManager.taskStart();
//				return AjaxResult.success(id+"任务启动成功!");
//			} catch (Exception e) {
//				logger.error("", e);
//			}
//	    	 return AjaxResult.error(id+"任务启动失败!");
//
//	    }
		
//		//hander
//		@RequestMapping(value="/ftp/hander",method= RequestMethod.POST)
//	    @ResponseBody
//	    public AjaxResult hander(String id) {
//	    	try {
//	    		ftpEngine.engin(filepath+LINE_TAG+"ftp"+LINE_TAG+id);
//				return AjaxResult.success(id+"作业操作成功!");
//			} catch (Exception e) {
//				logger.error("", e);
//			}
//	    	 return AjaxResult.error(id+"作业操作失败!");
//
//	    }
	    
//	    @RequestMapping(value="/ftp/stop",method= RequestMethod.POST)
//	    @ResponseBody
//	    public AjaxResult stop(String id) {
//	    	try {
//	    		File file = new File(filepath+LINE_TAG+"ftp"+LINE_TAG+id);
//	    		Configuration configuration = Configuration.from(file);
//	    		String name = configuration.getString(CommonKey.FTP_NAME_TAG);
//	    		TaskManager task = new TaskManager();
//	    		task.setJobName(name);
//	    		task.setGroupName(TaskManager.GROUP_NAME);
//	    		quartzManager.pauseTask(task);
//				 return AjaxResult.success(id+"任务停止成功!");
//			} catch (Exception e) {
//				logger.error("", e);
//			}
//	    	 return AjaxResult.error(id+"任务停止失败!");
//
//	    }


		    @RequestMapping(value="/ftp/remove",method= RequestMethod.POST)
	    @ResponseBody
	    public AjaxResult stop(String ids) {
	    	try {
	    		File f = new File(filepath+LINE_TAG+"ftp"+LINE_TAG+ids);

				FileUtils.forceDelete(f);
				 return AjaxResult.success(ids+"删除成功!");
			} catch (Exception e) {
				logger.error("", e);
			}
	    	 return AjaxResult.error(ids+"删除失败!");

	    }
	    
	    
	    
}
